<template>
    <div class="search-container">
         <el-input
            v-model="filterParams.title"
            placeholder="请输入标题"
            style="width: 180px"
            class="filter-item"
            clearable
            @change="emitFilterChange"
          />
          <el-date-picker
            v-model="filterParams.year"
            type="year"
            placeholder="选择年份"
            class="filter-item"
            style="width: 120px;margin-right: 20px;"
            @change="emitFilterChange"
          />
          <el-button
            class="filter-item"
            type="primary"
            :icon="Plus"
            @click="handleCreate"
          >
            新增
          </el-button>
          <el-button
            class="filter-item"
            type="primary"
            :icon="Search"
            @click="handleSearch"
          >
            搜索
          </el-button>
        </div>
        <el-table
          :data="tableData"
          border
          fit
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="标题" prop="title" min-width="160" />
          <el-table-column label="年份" prop="year" width="100" align="center" />
          <el-table-column label="指标值" prop="value" width="120" align="center" />
          <el-table-column label="附件" prop="files" min-width="180">
            <template #default="{ row }">
              <div v-if="row.files && row.files.length">
                <el-link v-for="(file, idx) in row.files" :key="file.uid || file.url || idx" :href="file.url" target="_blank" type="primary" style="margin-right: 8px;">
                  {{ file.name }}
                </el-link>
              </div>
              <span v-else style="color:#aaa">无</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="{ row }">
              <el-button type="primary" size="small" :icon="Edit" @click="handleEdit(row)" />
              <el-popconfirm title="确定删除该数据吗？" @confirm="handleDelete(row)">
                <template #reference>
                  <el-button
                    size="small"
                    type="danger"
                    :icon="Delete"
                  />
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="pagination.total"
          :page-size="pagination.pageSize"
          :current-page="pagination.currentPage"
          @update:current-page="handleCurrentChange"
          @update:page-size="handlePageSizeChange"
        />
        <el-dialog v-model="dialogVisible" :title="titleDialog" width="35%" :close-on-click-modal="false">
            <el-form :model="form" ref="formRef" label-width="100px" :rules="rules">
                <el-form-item label="标题" prop="title">
                    <el-input v-model="form.title" clearable/>
                </el-form-item> 
                <el-form-item label="年份" prop="year">
                    <el-date-picker v-model="form.year" type="year" placeholder="选择年份" style="width: 100%" />
                </el-form-item>
                <el-form-item label="指标值" prop="value">
                    <el-input-number v-model="form.value" :min="0" style="width: 100%" />
                </el-form-item>
                <el-form-item label="上传附件" prop="files">
                    <el-upload
                      v-model:file-list="form.files"
                      action="#"
                      :auto-upload="false"
                      :limit="5"
                      :on-remove="handleRemoveFile"
                      :on-change="handleFileChange"
                      list-type="text"
                    >
                      <el-button type="primary">选择文件</el-button>
                    </el-upload>
                </el-form-item>

            </el-form>
            <template #footer>  
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAdd">保存</el-button>
            </template>
        </el-dialog>
  </template>
  
  <script setup lang="ts">
  import { ref, reactive } from 'vue'
  import Pagination from '@/components/Pagination/index.vue'
  import { Delete, Edit,Plus,Search } from '@element-plus/icons-vue'
  
  const filterParams = reactive({
    title: '',
    year: '',
  })
  


  const dialogVisible = ref(false)
  const form = ref<FillItem>({
    id: undefined,
    title: '',
    year: '',
    value: 0,
    files: []
  })

  const rules = reactive({
    title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
    year: [{ required: true, message: '请选择年份', trigger: 'change' }],
    value: [{ required: true, message: '请输入指标值', trigger: 'blur' }],
  })
  
  const titleDialog = ref('新增')
  const formRef = ref()

 
  const emit = defineEmits(['delete', 'edit'])
  
  interface FileItem {
    name: string
    url?: string
    uid?: string | number
  }

  interface FillItem {
    id?: number
    title: string
    year: string
    value: number
    files: FileItem[]
  }

  const tableData = ref<FillItem[]>([])
  const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  })

  // 示例数据 - 实际应从API获取
  const mockData: FillItem[] = [
    {
      id: 1,
      title: '2023年人口总量',
      year: '2023',
      value: 1867,
      files: []
    },
    {
      id: 2,
      title: '2022年GDP',
      year: '2022',
      value: 28200,
      files: [
        { name: 'gdp报告.pdf', url: 'https://example.com/gdp.pdf' }
      ]
    }
  ]

  const fetchData = async () => {
    console.log('fetchData')
    try {
      // 实际项目中调用API
      // const res = await getIndicatorList({ 
      //   page: pagination.currentPage,
      //   size: pagination.pageSize 
      // })
      let filtered = mockData.filter(item => {
        let match = true
        if (filterParams.title) match = match && item.title.includes(filterParams.title)
        if (filterParams.year) match = match && item.year === String(filterParams.year)
        return match
      })
      tableData.value = filtered
      pagination.total = filtered.length
    } catch (error) {
      console.error('获取数据失败:', error)
    }
  }

  const handleCurrentChange = (page: number) => {
    pagination.currentPage = page
    fetchData()
  }

  const handlePageSizeChange = (size: number) => {
    pagination.pageSize = size
    fetchData()
  }

  const emitFilterChange = () => {
    console.log('筛选条件变更:', filterParams)  
    fetchData()
  }

  const handleCreate = () => {
    dialogVisible.value = true
    titleDialog.value = '新增'
    formRef.value?.resetFields()
    form.value = {
      id: undefined,
      title: '',
      year: '',
      value: 0,
      files: []
    }
  }

  const handleAdd = () => {
    dialogVisible.value = false
    if (titleDialog.value === '新增') {
      form.value.id = Date.now()
      tableData.value.push({ ...form.value })
    } else {
      tableData.value = tableData.value.map(item => item.id === form.value.id ? { ...form.value } : item)
    }
    fetchData()
  }


  const handleDelete = (row: FillItem) => {
    // console.log('删除指标', row);
    tableData.value = tableData.value.filter((item: FillItem) => item.id !== row.id)
    fetchData()
  }

  const handleEdit = (row: FillItem) => {
    // console.log('编辑指标', row)
    titleDialog.value = '编辑'
    dialogVisible.value = true
    form.value = JSON.parse(JSON.stringify(row))
  }

  const handleSearch = () => {
    console.log('搜索指标')
    fetchData()
  }

  const handleRemoveFile = (file: FileItem, fileList: FileItem[]) => {
    form.value.files = fileList
  }

  const handleFileChange = (file: any, fileList: FileItem[]) => {
    form.value.files = fileList
  }

  defineExpose({
    fetchData
  })

  fetchData()
</script>
<style scoped lang="scss">
.search-container {
     margin-bottom: 20px;
    
    .filter-item {
      margin-right: 10px;
    }
}
</style>